//
//  ViewController.m
//  canScroll
//
//  Created by MB__Lee on 2019/2/28.
//  Copyright © 2019年 MB__Lee. All rights reserved.
//

#import "ViewController.h"
#import "MBScroolView.h"
#import "MBTableView.h"

#define Screen_width [UIScreen mainScreen].bounds.size.width
#define Screen_hight [UIScreen mainScreen].bounds.size.height
#define Marin 200

@interface ViewController ()<UIScrollViewDelegate>

@property(nonatomic,strong)MBScroolView *scrollview;

@property(nonatomic,strong)MBTableView *tableview;

@property(nonatomic,assign)BOOL canScrool;

@end

@implementation ViewController
-(MBTableView *)tableview{
    if (!_tableview) {
        MBTableView *tableview = [[MBTableView alloc]initWithFrame:CGRectMake(0, Marin, Screen_width, Screen_hight) style:UITableViewStylePlain];
        _tableview = tableview;
        
        
        
    }
    return  _tableview;
}
-(MBScroolView *)scrollview{
    if (!_scrollview) {
        MBScroolView *scroll = [[MBScroolView alloc] initWithFrame:self.view.bounds];
        _scrollview = scroll;
        
        _canScrool = YES;
        scroll.delegate = self;
        scroll.contentSize = CGSizeMake(Screen_width, Screen_hight + Marin);
        scroll.backgroundColor = [UIColor blueColor];
        
    }
    return  _scrollview;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview: self.scrollview];
    [self.scrollview addSubview:self.tableview];
    
    
//    监听scrollview 上的tableview 是否在偏移量为0 的位置
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginScroll:) name:@"subAtZero" object:nil];
}

#pragma mark ---悬停关键代码---通知+ scrollview 代理方法+ canScrollview 参数+ 手势协议
-(void)beginScroll:(NSNotification *)noti{
    
    _canScrool = YES;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat y = scrollView.contentOffset.y;
    CGPoint mboffset = scrollView.contentOffset;
    

    if (_canScrool == YES) { // 可以滚动的时候
        if (y > Marin) {
            mboffset.y = Marin;
            [scrollView setContentOffset:mboffset];
            _canScrool = NO;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"atTop" object:nil];
        }else{
            [scrollView setContentOffset:mboffset];
        }
    }else{
        mboffset.y = Marin;
        [scrollView setContentOffset:mboffset];
    }
    
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
